#!/bin/csh 

# -----------------------------------------------------
# Launcher for: Observer Support System Watchdog. (OSW).
# -----------------------------------------------------

# osw [ start | stop ] <model>

if (${#argv} < 2) then
    echo "Usage: osw [ start | stop ] <model>"
    echo "       model: scope"
    exit 1
endif

source /opt/ngat/etc/cshrc
 
source ${DEPLOY_BIN}/class_setup
source ${DEPLOY_BIN}/osx_setup

set model = $2

#source $OSS_CONFIG/${model}_osw_args

set DAT = `date -u +"%j"`
set NOW = `date -u`
set OSW_CONSOLE_LOG_FILE = ${DEPLOY_TMP}/osw_${model}.log

$DEPLOY_ETC/log_roll $OSW_CONSOLE_LOG_FILE 100000 3


#-----------------------------------------------------------
# StartCodes. ( These are exit codes for various OSS halts).
#-----------------------------------------------------------

set RESTART_CODE  = 5
set STOP_CODE     = 4

set PID = $DEPLOY_TMP/osw_${model}.pid

switch ($1)

    case stop:

	echo "Observer Support System Watchdog stopping $NOW "  >>& $OSW_CONSOLE_LOG_FILE
	
	if (! -e $PID) then
	    echo "Cannot locate a PID file: $PID "  >>& $OSW_CONSOLE_LOG_FILE
	    exit 1
	endif
	set AID = `cat $PID` 
    
	if ($AID == "") then
	    echo "$PID does not contain a valid PID for the OSW" >>& $OSW_CONSOLE_LOG_FILE
	    exit 2
	endif

	set BID = `ps -ef | grep $AID | awk '{if ($3 == '$AID') print $2}'`

	kill -9 $AID  

	su -c "$DEPLOY_BIN/osx stop" occ

	kill -9 $BID

	rm -f $PID

	breaksw

    case start:

	echo "Observer Support System Watchdog starting $NOW " >>& $OSW_CONSOLE_LOG_FILE

	echo $$ > $PID
      
	echo "Testwhile - start in 60 seconds" >>& $OSW_CONSOLE_LOG_FILE

	set code = $RESTART_CODE

	while ($code != $STOP_CODE)

	    sleep 10

	    # while code != STOP_CODE = stop OSW as well as OSS
	    switch (${code})

	    case ${RESTART_CODE}:
		set NOW = `date -u`
		echo "Starting OSS $NOW" >>& $OSW_CONSOLE_LOG_FILE
		su -c "$DEPLOY_BIN/osx auto" occ  >>& $OSW_CONSOLE_LOG_FILE
		set code = $status
		breaksw

	    endsw	
	    set NOW = `date -u`
	    echo "OSW process exit with status $code $NOW" >>& $OSW_CONSOLE_LOG_FILE
 
	end
	breaksw
endsw

set NOW = `date -u`
echo "Leaving OSW Wrapper $NOW"  >>& $OSW_CONSOLE_LOG_FILE
rm -f $PID
